package logic

import (
	"context"
	"fmt"
	"shopping-cart/model"

	"shopping-cart/cartrpc/cartrpc"
	"shopping-cart/cartrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cartrpc.CartAddRequest) (*cartrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var shop model.Shop
	err := model.DB.Debug().Where("id=?", in.ShopId).First(&shop).Error
	if err != nil {

		return nil, fmt.Errorf("该商品不存在")
	}
	if in.Quantity > int64(shop.Num) {

		return nil, fmt.Errorf("商品库存不足")
	}
	var cart model.Cart
	if in.ShopId == int64(cart.ShopId) {

		cart.Quantity += int(in.Quantity)
		model.DB.Debug().Where("id=?", in.ShopId).Updates(&cart)
	} else {
		cart = model.Cart{
			ShopId:   int(in.ShopId),
			Quantity: int(in.Quantity),
			Money:    float64(in.Money),
		}
		model.DB.Debug().Create(&cart)
	}
	return &cartrpc.CartAddResponse{
		CartAdd: int64(cart.ID),
	}, nil
}
